//时间戳实现  第一次触发
//顾头 不顾尾
function throttle1(func,wait) {
    let context,args;

    let old = 0;
    return function(){
        context = this;
        args = arguments;
        let now = new Date().valueOf();

        if((now-old)> wait){
            func.apply(context,args)
            old = now
        }
    }
}
//第一次不会触发  最后一次会触发
function throttle2(func,wait) {
    let context,args,timeout;
    return function(){
        context = this;
        args = arguments;
        if(!timeout){
            timeout= setTimeout(()=>{
                timeout = null;  //清空
                func.apply(context,args)
            },wait)
        }
    }
}
//第一次执行，最后一次也会执行
function throttle3(func,wait) {
    let context,args,timeout,old=0;
    return function(){
        context = this;
        args = arguments;
        let now = new Date().valueOf();

        if((now-old)> wait){
            if(timeout){
                clearTimeout(timeout);
                timeout = null;
            }
            func.apply(context,args);
            old = now
        }else if(!timeout){
            timeout= setTimeout(()=>{
                old = new Date().valueOf();
                timeout = null;  //清空
                func.apply(context,args)
            },wait)
        }
    }
}

function throttle(func,wait,options) {
    let context,args,timeout,old=0;
    if(!options) options = {};
    let later =  ()=>{
        old = new Date().valueOf();
        timeout = null;  //清空
        func.apply(context,args)
    }
    return function(){
        context = this;
        args = arguments;
        let now = new Date().valueOf();
        if(options.leading === false && !old){
            old = now
        }
        if((now-old)> wait){
            if(timeout){
                clearTimeout(timeout);
                timeout = null;
            }
            func.apply(context,args);
            old = now
        }else if(!timeout && options.trailing !==false){
            timeout= setTimeout(later,wait)
        }
    }
}

var count = 0;
var container = document.querySelector('#container');
function doSomeThing(e) {
    // console.log(this);
    // console.log(e);   //undefined
    // 发请求或进行复杂的计算比较耗性能
    container.innerHTML = count++;
}
container.onmousemove=throttle(doSomeThing,2000,{leading:true,trailing:true})
